package com.song.controller.user;

import com.song.result.Result;
import com.song.service.DishService;
import com.song.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController("user-DishController")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;
    //根据分类id查询菜品
    @Cacheable(cacheNames = "dishCache",key = "#categoryId")
    @GetMapping("/list")
    public Result<List<DishVO>> getDishListByCategoryId(Long categoryId){
        log.info("根据分类id查询菜品及其口味,参数id：{}",categoryId);
        //1.从redis中查询数据
        String key =  "dish_"+categoryId;
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (dishVOList != null && dishVOList.size() > 0) return  Result.success(dishVOList,"查询成功");
        //2.缓存中没有数据，查询数据库
        List<DishVO> dishList =  dishService.getDishAndFlavorList(categoryId);
        // 3.将数据保存到redis中
         redisTemplate.opsForValue().set(key,dishList);
        return Result.success(dishList,"分类查询菜品成功");
    }
}
